﻿using System;
using RabbitMQ.Client;
using RabbitMQ.Client.Framing.Impl.v0_8;

namespace YEA.Infrastructure.Gateway
{
    public class Publisher : YEA.Infrastructure.Gateway.IPublisher
    {
        protected IConnection _connection;
        private ConvertToMessage _converter;
        protected IModel _channel;
        public string Exchange { get; internal set; }
        public bool Mandatory { get; internal set; }
        public bool Immediate { get; internal set; }
        public Publisher(IConnection connection, ConvertToMessage converter, string exchange)
        {
            if (connection == null)
                throw new ApplicationException("The connection parameter is missing.  A connection is required to publish messages");
            if (converter == null)
                throw new ApplicationException("The converter is missing and is required to convert the object to a message for publishing");
            if (string.IsNullOrWhiteSpace(exchange))
                throw new ApplicationException("The exchange parameter is missing.  An exchange is required to receive the messages we publish");
            Exchange = exchange;
            _connection = connection;
            _converter = converter;
            _channel = _connection.CreateModel();
        }
        public void Publish(object ObjectToPublish)
        {
            if (ObjectToPublish == null)
                throw new ApplicationException("The ObjectToPublish is missing and is required to publish content to the Message bus");
            if (!_connection.IsOpen || _channel.IsClosed)
            {
                if (_connection.CloseReason != null)
                {
                    throw new ApplicationException(_connection.CloseReason.ReplyText);
                }
                _channel.Dispose();
                _channel = _connection.CreateModel();
            }
            var message = _converter(_channel, ObjectToPublish);
            message.Properties.DeliveryMode = 2;
            _channel.BasicPublish(Exchange, message.RoutingKey, message.Properties, message.Body);
            
        }
    }
}
